<template>
  <div class="maingl">
    <div class="main_spac1">
      <div class="main_white padding10">
        <div class="main_crumbs">
          <div class="main_crumbs_l">
            <a href="javascript:;" @click="$router.back(-1)">
              <i class="el-icon-arrow-down"></i>返回
            </a>
            <em>|</em>
            <span>授权</span>
          </div>
        </div>

        <div class="main_tree">
          <h3 class="main_tree_h">菜单名称</h3>
          <div class="main_tree_b">
            <el-tree
              :data="list"
              :check-strictly="true"
              show-checkbox
              node-key="id"
              ref="tree"
              v-loading="listLoading"
              element-loading-text="加载中"
              icon-class="el-icon-arrow-right"
              :default-checked-keys="defaultkeys"
              :default-expanded-keys="defaultexpandedkeys"
              highlight-current
              :props="defaultProps"
              style="min-height: 530px"
              @check-change="handleCheckChange"
              @check="checkChange"
            ></el-tree>
          </div>
        </div>

        <div class="newConBox_p100 paddingBottom10" id="newConBox">
          <div class="newConBox_h32">
            <div :class="['newConBox ', { on: searchBarFixed }]">
              <el-button type="primary" @click="Grant" v-repeatClick
                >确认授权</el-button
              >
              <el-button @click="$router.back(-1)">取消</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { role_auth, role_accredit } from "@/api/global/globalRole";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";

export default {
  components: {},
  data() {
    return {
      // 列表数据
      list: [],
      listLoading: false,
      // 树型tree
      defaultkeys: [],
      defaultexpandedkeys: [-1],
      defaultProps: {
        children: "selfNext",
        label: "name",
      },

      // id
      id: this.$route.params.id,
      // 监听滚动
      searchBarFixed: false,
      isEdit: false,
    };
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  methods: {
    handleCheckChange(data, checked, indeterminate) {
      this.isEdit = true;
    },
    // 监听滚动
    handleScroll() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      scrollTop + document.documentElement.clientHeight >
      document.getElementById("newConBox").offsetTop + 200
        ? (this.searchBarFixed = false)
        : (this.searchBarFixed = true);
    },
    // 确认授权
    Grant() {
      this.isEdit = false;
      let arry = this.$refs.tree
        .getCheckedKeys()
        .concat(this.$refs.tree.getHalfCheckedKeys());
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name), {
              role_id: this.id,
              ids: JSON.stringify(arry.filter((item) => item)),
            }) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          role_id: this.id,
          ids: JSON.stringify(arry.filter((item) => item)),
        }
      );
      role_accredit(data).then((res) => {
        if (res.errcode == 0) {
          this.$message({
            message: "授权成功",
            type: "success",
          });
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 菜单列表
    role_auth() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name), { id: this.id }) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: this.id }
      );
      role_auth(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          let arry = [];
          res.data.list.map((e) => {
            if (e.isSelect) {
              arry.push(e.id);
              if (e.selfNext.length != 0) {
                this.selfNext(e.selfNext, arry);
              }
            }
          });
          this.defaultkeys = arry;
          this.list = [
            {
              id: -1,
              isSelect: true,
              name: "所有菜单",
              selfNext: res.data.list,
            },
          ];
          // this.list = res.data.list;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    selfNext(self, arry) {
      self.map((e) => {
        if (e.isSelect) {
          arry.push(e.id);
          if (e.selfNext.length != 0) {
            this.selfNext(e.selfNext, arry);
          }
        }
      });
    },
    /* 
    节点选择的change事件
    父节点选中，子节点全部选中,
    子节点可以一个个取消，父节点依然选中 
    */

    checkChange(data) {
      const node = this.$refs.tree.getNode(data.id);
      this.setNode(node);
    },
    setNode(node) {
      if (node.checked) {
        this.setParentNode(node);
        this.setChildNodeSelected(node);
      } else {
        this.setChildNode(node);
      }
    },
    // 向上递归，选中子级，父级逐级选中
    setParentNode(node) {
      if (node.parent) {
        for (const key in node) {
          if (key === "parent") {
            node[key].checked = true;
            this.setParentNode(node[key]);
          }
        }
      }
    },
    // 向下递归，选中父级，子级全部选中
    setChildNodeSelected(node) {
      if (node.childNodes.length > 0) {
        node.childNodes.map((e) => {
          e.checked = true;
          this.setChildNodeSelected(e);
        });
      }
    },
    //递归设置子节点全部取消选中
    setChildNode(node) {
      if (node.childNodes && node.childNodes.length) {
        node.childNodes.forEach((item) => {
          item.checked = false;
          this.setChildNode(item);
        });
      }
    },
  },

  beforeRouteLeave(to, from, next) {
    if (this.isEdit) {
      setTimeout(() => {
        this.$confirm(
          "您已经有数据操作，离开页面系统不会保存您的操作，确定离开吗？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            // 正常跳转
            next();
          })
          .catch(() => {
            next(false);
          });
      }, 200);
    } else {
      next();
    }
  },
  created() {
    // 菜单列表
    this.role_auth();
  },
};
</script>
<style lang="scss" scoped>
.maingl {
  .main_table {
    margin-top: 20px;
    /deep/.el-table--border th:first-child .cell {
      padding-left: 70px;
    }
    /deep/.el-table--border td:first-child .cell {
      padding-left: 60px;
    }
    .maingl_ch {
      display: inline-block;
      margin-left: 10px;
      /deep/.el-checkbox__label {
        padding-left: 10px;
      }
    }
  }
  .newConBox.on {
    margin-left: -10px;
    padding-left: 10px;
  }
}
</style>
